package com.dragon.logical.service.reminder.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.logical.service.auth.IDictsortDetailService;
import com.dragon.logical.service.avttendance.impl.AttendanceLeaveServiceImpl;
import com.dragon.logical.service.contract.IRefundService;
import com.dragon.logical.service.contract.IRejectedService;
import com.dragon.logical.service.finance.IPaymentService;
import com.dragon.logical.service.netty.NettyClientService;
import com.dragon.logical.service.protoBuilder.ProtoMessageBuilder;
import com.dragon.logical.service.reminder.IDoReminderService;
import com.dragon.logical.service.supplies.IProcurementService;
import com.dragon.logical.service.supplies.IPurchaseRequisitionService;
import com.dragon.protoJo.bean.msg.ProtoMsg;
import com.dragon.repository.entity.*;
import com.dragon.repository.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 待办提醒 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-06-27
 */
@Service
public class DoReminderServiceImpl extends ServiceImpl<DoReminderMapper, DoReminder> implements IDoReminderService {

    @Autowired
    DoReminderMapper mapper;
    @Autowired
    NettyClientService nettyClientService;
    @Autowired
    IDictsortDetailService detailService;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    QuotesMapper quotesMapper;
    @Autowired
    ContractMapper contractMapper;
    @Autowired
    ProduceMapper produceMapper;
    @Autowired
    DeliverMapper deliverMapper;
    @Autowired
    PlanCollectMapper planCollectMapper;
    @Autowired
    CustomerPaymentMapper customerPaymentMapper;
    @Autowired
    FollowMapper followMapper;
    @Autowired
    LoanMapper loanMapper;
    @Autowired
    ReimbursementMapper reimbursementMapper;
    @Autowired
    AttendanceMapper attendanceMapper;
    @Autowired
    AttendanceChildMapper attendanceChildMapper;
    @Autowired
    IPaymentService paymentService;
    @Autowired
    IProcurementService procurementService;
    @Autowired
    IPurchaseRequisitionService purchaseRequisitionService;
    @Autowired
    IRejectedService rejectedService;
    @Autowired
    AttendanceLeaveMapper attendanceLeaveMapper;
    @Autowired
    IRefundService refundService;


    @Override
    public Page<DoReminder> selectPageList(Integer adminId, Integer status, Integer page, Integer limit) {
        Page<DoReminder> reminderPage = new Page<>(page, limit);
        Page<DoReminder> doReminderPage = mapper.selectPageByAdminId(reminderPage, adminId, status);
        // 获取发送人的基本信息
        return doReminderPage;
    }


    @Override
    public void addDoReminder(DoReminder doReminder) {
        String standby = "";
        switch (doReminder.getType()) {
            case 8:
                //
                standby = doReminder.getTitle().concat(",请合理安排你的日程");
                break;
            case 9:
                Date date = new Date();
                String dd = new SimpleDateFormat("yyyy-MM-dd").format(date);
                Attendance attendance = attendanceMapper.selectOne(new QueryWrapper<Attendance>().lambda()
                        .eq(Attendance::getAdminId, doReminder.getAdminId())
                        .apply(" date_format(create_time,'%y-%mm-%dd') = date_format('" + dd + "','%y-%mm-%dd')"));

                String type = null;
                List<AttendanceChild> attendanceChildren = attendanceChildMapper.selectList(new QueryWrapper<AttendanceChild>()
                        .lambda().eq(AttendanceChild::getAttendanceId, attendance.getId()));
                // 获取打卡模版消息
                if (attendanceChildren.size() == 1){
                    type = "上班";
                } else {
                    type = "下班";
                }
                DictsortDetail clockDetail = detailService.selectNameByCodeAndValue("noticeCode", doReminder.getType());
                standby = clockDetail.getStandby()
                        .replace("{time}", new SimpleDateFormat("HH:ss").format(DateUtil.date()))
                        .replace("{type}", type);
                break;
            default:
                // 获取发送人名称
                Admin admin = adminMapper.selectById(doReminder.getFromId());
                // 获取模版消息
                DictsortDetail detail = detailService.selectNameByCodeAndValue("noticeCode", doReminder.getType());
                DictsortDetail dictsortDetail = detailService.selectNameByCodeAndValue("streamCode", doReminder.getOperationType());
                standby = detail.getStandby()
                        .replace("{username}", admin.getUsername()) //替换用户名
                        .replace("{operationName}", dictsortDetail.getName()) //替换流程类型
                        .replace("{title}", selectOperationTitleById(doReminder.getOperationType(), doReminder.getCorrlelationId())); //替换关联id标题
                //获取关联数据标题
                if (doReminder.getType() == 4) {
                    Admin auditAdmin = adminMapper.selectById(doReminder.getNextAdminId());
                    standby = standby.replace("{auditName}", auditAdmin.getUsername());
                }
                // 获取会签或者并签提醒数据
                if (doReminder.getType() == 6 || doReminder.getType() == 7) {
                    if (doReminder.getAdminIds() != null && doReminder.getAdminIds().size() != 0) {
                        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().in(Admin::getId, doReminder.getAdminIds());
                        List<Admin> adminList = adminMapper.selectList(queryWrapper);
                        String adminNameSet = adminList.stream().map(Admin::getUsername).collect(Collectors.joining(","));
                        standby = standby.replace("{nameSet}", adminNameSet);
                    }
                }
                break;
                // 同意申请修改提醒
            case 10:
                // 获取发送人名称
                Admin admin1 = adminMapper.selectById(doReminder.getFromId());
                // 获取模版消息
                DictsortDetail noticeCode = detailService.selectNameByCodeAndValue("noticeCode", doReminder.getType());
                DictsortDetail streamCode = detailService.selectNameByCodeAndValue("streamCode", doReminder.getOperationType());
                standby = noticeCode.getStandby()
                        .replace("{username}",admin1.getUsername())
                        .replace("{title}",selectOperationTitleById(doReminder.getOperationType(),doReminder.getCorrlelationId()))
                        .replace("{operationName}",streamCode.getName());
                break;
                // 提交申请修改提醒
            case 11:
                Admin admin2 = adminMapper.selectById(doReminder.getFromId());
                // 获取模版消息
                DictsortDetail noticeCode1 = detailService.selectNameByCodeAndValue("noticeCode", doReminder.getType());
                DictsortDetail streamCode1 = detailService.selectNameByCodeAndValue("streamCode", doReminder.getOperationType());
                standby = noticeCode1.getStandby()
                        .replace("{username}",admin2.getUsername())
                        .replace("{title}",selectOperationTitleById(doReminder.getOperationType(),doReminder.getCorrlelationId()))
                        .replace("{operationName}",streamCode1.getName());
                break;

        }
        doReminder.setTitle(standby);
        // 添加到数据中
        mapper.insert(doReminder);
        // 并发送websocket消息，如果在线则直接发送，如果不在线则推送信息
        ProtoMsg.Message noticeMessage = ProtoMessageBuilder.buildNotifyMessage(doReminder);
        Boolean result = nettyClientService.sendMsg(null, noticeMessage);

        //如果result为false，则执行推送消息
        if (result == null || result == false) {

        }
    }


    /**
     * 获取对应数据标题
     *
     * @param operationType 流程类型
     * @param relationId    关联的id
     * @return
     */
    public String selectOperationTitleById(Integer operationType, Integer relationId) {
        String title = "";
        switch (operationType) {

            //报价
            case 1:
                Quotes quotes = quotesMapper.selectById(relationId);
                title = quotes.getQuotesName();
                break;
            //合同
            case 2:
                Contract contract = contractMapper.selectById(relationId);
                title = contract.getName();

                break;
            //生产
            case 3:
                Produce product = produceMapper.selectById(relationId);
                title = product.getName();

                break;
            //送货
            case 4:
                Deliver deliver = deliverMapper.selectById(relationId);
                title = deliver.getName();

                break;
            //回款
            case 5:
                CustomerPayment payment = customerPaymentMapper.selectById(relationId);
                title = payment.getPaymentName();
                break;
            //回款计划
            case 6:
                PlanCollect planCollect = planCollectMapper.selectById(relationId);
                title = planCollect.getTractName();

                break;
            //跟进记录
            case 7:
                Follow follow = followMapper.selectById(relationId);
                title = follow.getContent();

                break;
            //报销
            case 8:
                Reimbursement reimbursement = reimbursementMapper.selectById(relationId);
                title = reimbursement.getReimbursementName();
                break;
            //借款
            case 9:
                Loan loan = loanMapper.selectById(relationId);
                title = loan.getLoanName();
                break;
            //客户
            case 10:
                Customer customer = customerMapper.selectById(relationId);
                title = customer.getCustomerName();
                break;
        }
        return title;
    }

    @Override
    public Object selectOperationDetailBy(Integer operationType, Integer relationId) {
        Object object = null;
        switch (operationType) {
            //报价
            case 1:
                Quotes quotes = quotesMapper.selectById(relationId);
                if (quotes != null) {
                    Admin adminQ = adminMapper.selectById(quotes.getRecodeId());
                    quotes.setApplicantName(adminQ.getUsername());
                    object = quotes;
                }
                break;
            //合同
            case 2:
                Contract contract = contractMapper.selectById(relationId);
                if (contract != null) {
                    Admin adminC = adminMapper.selectById(contract.getAdminId());
                    contract.setApplicantName(adminC.getUsername());
                    object = contract;
                }
                break;
            //生产
            case 3:
                Produce product = produceMapper.selectById(relationId);
                if (product != null) {
                    Admin adminP = adminMapper.selectById(product.getResponsibleId());
                    Admin adminP2 = adminMapper.selectById(product.getAdminId());
                    product.setResponsibleName(adminP.getUsername());
                    product.setApplicantName(adminP2.getUsername());
                    object = product;
                }
                break;
            //送货
            case 4:
                Deliver deliver = deliverMapper.selectById(relationId);
                if (deliver != null) {
                    Admin adminD = adminMapper.selectById(deliver.getDeliveryId());
                    Admin adminD2 = adminMapper.selectById(deliver.getAdminId());
                    deliver.setDeliveryName(adminD.getUsername());
                    deliver.setApplicantName(adminD2.getUsername());
                    object = deliver;
                }
                break;
            //回款
            case 5:
                CustomerPayment payment = customerPaymentMapper.selectById(relationId);
                if (payment != null) {
                    Admin adminCP = adminMapper.selectById(payment.getAdminId());
                    payment.setAdminName(adminCP.getUsername());
                    object = payment;
                }
                break;
            //回款计划
            case 6:
                PlanCollect planCollect = planCollectMapper.selectById(relationId);
                if (planCollect != null) {
                    object = planCollect;
                }
                break;
            //跟进记录
            case 7:
                Follow follow = followMapper.selectById(relationId);
                if (follow != null) {
                    Admin adminF = adminMapper.selectById(follow.getAdminId());
                    follow.setApplicantName(adminF.getUsername());
                    object = follow;
                }
                break;
            //报销
            case 8:
                Reimbursement reimbursement = reimbursementMapper.selectById(relationId);
                if (reimbursement != null) {
                    object = reimbursement;
                }
                break;
            //借款
            case 9:
                Loan loan = loanMapper.selectById(relationId);
                if (loan != null) {
                    object = loan;
                }
                break;
            //客户
            case 10:
                Customer customer = customerMapper.selectById(relationId);
                if (customer != null) {
                    Admin admin = adminMapper.selectById(customer.getAdminId());
                    customer.setApplicantName(admin.getUsername());
                    object = customer;
                }
                break;
            //请假
            case 13:
                AttendanceLeave attendanceLeave = attendanceLeaveMapper.selectDetail(relationId);
                if (attendanceLeave != null) {
                    object = attendanceLeave;
                }
                break;
            //付款 15
            case 15:
                Payment paymentById = paymentService.getPaymentById(relationId);
                if (paymentById != null){
                    object = paymentById;
                }
                break;
            //退款
            case 16:
                Refund refund = refundService.selectDetailById(relationId);
                if (refund != null){
                    object = refund;
                }
                break;
            //请购 22
            case 22:
                PurchaseRequisition purchaseRequisition = purchaseRequisitionService.detailById(relationId);
                if (purchaseRequisition != null){
                    object = purchaseRequisition;
                }
                break;
            //采购 23
            case 23:
                Procurement procurement = procurementService.detailById(relationId);
                if (procurement != null){
                    object = procurement;
                }
                break;
            //退货 24
            case 24:
                Procurement returnProcurement = procurementService.detailById(relationId);
                if (returnProcurement != null){
                    object = returnProcurement;
                }
                break;
            //生产退货 25
            case 25:
                Rejected rejected = rejectedService.selectDetailById(relationId);
                if (rejected != null){
                    object = rejected;
                }
                break;
        }
        return object;
    }

    @Override
    public void upStat(String id) {
        List<Integer> list = Arrays.asList(id.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        for (Integer integer : list) {
            DoReminder doReminder = mapper.selectById(integer);
            doReminder.setStatus(1);
            mapper.updateById(doReminder);
        }
    }

    @Override
    public Page<DoReminder> getToDoList(Integer page, Integer limit, Integer adminId) {
        Page<DoReminder> pa = new Page<>(page, limit);
        Page<DoReminder> selectToDo = mapper.selectToDo(pa, adminId);
        return selectToDo;
    }

    @Override
    public Page<DoReminder> getMessageList(Integer page, Integer limit, Integer adminId) {
        Page<DoReminder> pa = new Page<>(page, limit);
        Page<DoReminder> selectMessage = mapper.selectMessage(pa, adminId);
        return selectMessage;
    }
}
